﻿using Common;
using DataLibrary;
using System.Web;
using System.Web.Mvc;

namespace ImageWeb.Controllers
{
    public class AdminAuthorize : AuthorizeAttribute
    {
        readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private ImageManagerEntities ime = new ImageManagerEntities();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Session["UserID"] != null && RedisHelper.Get<string>(httpContext.Session["UserID"].ToString()) != null)
            {
                string oldSessionid = RedisHelper.Get<string>("web" + httpContext.Session["UserID"].ToString());
                if (httpContext.Session.SessionID != oldSessionid)
                {
                    httpContext.Session.Clear();
                    HttpCookie cookie = new HttpCookie("ForcedOff");
                    cookie.Value = httpContext.Request.UserHostAddress;
                    cookie.Expires.AddSeconds(30);
                    HttpContext.Current.Response.AppendCookie(cookie);
                }
            }
            if (httpContext.Session["UserID"] == null)
            {
                return false;
            }
            else
            {
                int roleid = int.Parse(httpContext.Session["RoleID"].ToString());                
                return checkRole(roleid, httpContext);
            }
        }

        /// <summary>
        /// 重写未授权的 HTTP 请求处理
        /// </summary>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("~/Login/Login");
            HttpCookie cookie = new HttpCookie("unauthorized");
            cookie.Value = "unauthorized";
            cookie.Expires.AddSeconds(30);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        
        private bool checkRole(int roleid, HttpContextBase httpContext)
        {
            string url = httpContext.Request.Path;
            string[] _params = url.Split('/');
            string _controller = "";
            string _action = "";
            if (_params.Length > 1)
            {
                _controller = _params[1];
                _action = _params.Length > 2 ? _params[2] : "Index";
            }
            else
            {
                _controller = "Home";
                _action = "Index";
            }
            
            if (_action.ToLower().Contains("edit") || _action.ToLower().Contains("delete"))
            {
                if (roleid != 1)
                {
                    logger.Warn("用户" + httpContext.Session["UserNum"].ToString() + "(ip:" + httpContext.Request.UserHostAddress + ")试图访问" + _controller + "控制器下的" + _action + "动作，因没有权限被拒绝！");
                    return false;
                }                
            }
            else
            {
                logger.Debug("用户" + httpContext.Session["UserNum"].ToString() + "(ip:" + httpContext.Request.UserHostAddress + ")访问了" + _controller + "控制器下的" + _action + "动作！");
            }
            return true;
        }
       
    }
}